<?php
require_once dirname(dirname(dirname(dirname(__FILE__)))) . '/init.php';

/**
 *向oms获取订单占用量
 */
class OrderOccupyAmountController extends Controller_CronJob {
	public function run() {
		$domain = Helper_Config::get('url', 'oms', 'url');
		//oms每天凌晨4点更新，我们取凌晨以后的值
		$startTime = mktime(0, 0, 0);
		$endTime = time();
		$data = $startTime . '-' . $endTime;
		try {
			$url = $domain . 'interface/amoutused/getused';
			$result = Requests::GET($url . '?ctime=' . $data);
		} catch (Exception $e) {
			$errorMsg = '向oms获取订单占用量出错，错误原因:' . $e->getMessage();
			$this->log->record($errorMsg, Log::ALERT);
			die($errorMsg);
		}
		$result = json_decode($result->body, true);
		if (json_last_error() != JSON_ERROR_NONE) {
			$errorMsg = 'oms返回的订单占用量数据异常，错误原因:' . json_last_error_msg();
			$this->log->record($errorMsg, Log::ALERT);
			die($errorMsg);
		}

		if ($result['status'] != 1) {
			$errorMsg = '获取oms订单占用量数据异常，错误原因:' . $result['msg'];
			$this->log->record($errorMsg, Log::ALERT);
			die($errorMsg);
		}

		if (count($result['data']) > 0) {
			$this->writeDb->beginTransaction();
			try {
				//oms只传有订单占用的商品数据，所以我们先重置所有记录
				$initWhere = 'order_occupy !=0 AND order_occupy_quarter!=0';
				$this->writeDb->update('p_product_warehouse_stock', ['order_occupy' => 0, 'order_occupy_quarter' => 0], $initWhere);

				foreach ($result['data'] as $values) {
					$sql = 'UPDATE p_product_warehouse_stock SET order_occupy = ' . $values['total'] . ', order_occupy_quarter = ' . $values['d90'] . ' WHERE  goods_sn = "' . $values['sku'] . '" AND warehouse_code = "' . $values['stock_code'] . '"';
					$this->writeDb->query($sql);
				}
				$this->writeDb->commit();
				$this->log->record('订单占用量数据更新成功！');
				die('订单占用量数据更新成功！');
			} catch (Exception $e) {
				$this->writeDb->rollBack();
				$errorMsg = '订单占用量数据更新异常，错误原因:' . $e->getMessage();
				$this->log->record($errorMsg, Log::ALERT);
				die($errorMsg);
			}
		}
		$errorMsg = '订单占用量数据数据返回为空！';
		$this->log->record($errorMsg, Log::ALERT);
		die($errorMsg);
	}
}

$synOrderOccupyAmount = new OrderOccupyAmountController();
$synOrderOccupyAmount->run();